package com.hou.controller;

import com.hou.EX.uploadException.FileEmptyException;
import com.hou.EX.uploadException.FileSizeException;
import com.hou.EX.uploadException.FileTypeException;
import com.hou.pojo.UserBasic;
import com.hou.pojo.Vip;
import com.hou.vo.CaseVip;
import com.hou.vo.TaomiGoods;
import com.hou.service.TaomiGoodsService;
import com.hou.vo.JsonResult;
import com.hzk.vo.RespBean;
import com.hzk.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/hou")
public class TaomiGoodsController extends BaseController{
    @Autowired
    TaomiGoodsService taomiGoodsService;

    /** 头像文件大小的上限值(10MB) */
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    /** 允许上传的头像的文件类型 */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    @RequestMapping("/Taomiadd")
    public JsonResult taomiadd(@CaseVip Vip vip, TaomiGoods taomiGoods, UserBasic user) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        /*if (user == null){
            return new JsonResult<>(444,"登录过期请重新登录",null);
        }*/
        taomiGoodsService.addTaomiGoods(taomiGoods);
        List<TaomiGoods> select = taomiGoodsService.selectTaomiGoodsList();
        return new JsonResult<>(OK,"添加成功",select);
    }

    @RequestMapping("/Taomidelete")
    public JsonResult taomidelete(@CaseVip Vip vip,Long id) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        taomiGoodsService.deleteTaomiGoods(id);
        return new JsonResult<>(OK,"删除成功",null);
    }

    @RequestMapping("/Taomiupdate")
    public JsonResult taomiupdate(@CaseVip Vip vip,TaomiGoods taomiGoods) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        taomiGoodsService.updateTaomiGoods(taomiGoods);
        return new JsonResult<>(OK,"修改成功",null);
    }

//    @RequestMapping("/Taomiselect")
//    public TaomiGoods taomiselect(String goodsname) {
//        return taomiGoodsService.selectTaomiGoods(goodsname);
//    }
    @RequestMapping("/Taomiselect")
    public JsonResult taomiselect(@CaseVip Vip vip,String name) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        List<TaomiGoods> select = taomiGoodsService.selectTaomiGoods(name);
        if (select==null){
            return new JsonResult<>(OK,"查找数据失败",null);
        }
//        return RespBean.success(select);
        return new JsonResult<>(OK,"查找数据成功",select);
    }

    @RequestMapping("/Taomiselectid")
    public JsonResult taomiselectid(@CaseVip Vip vip,Long id) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        TaomiGoods taomiGoods = taomiGoodsService.selectidTaomiGoods(id);
        return new JsonResult<>(OK,"查找原来数据成功",taomiGoods);
    }

    @RequestMapping("/TaomiselectLists")
    public JsonResult taomiselect(@CaseVip Vip vip) {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        List<TaomiGoods> select = taomiGoodsService.selectTaomiGoodsList();
        if (select==null){
            return new JsonResult<>(OK,"查找数据失败",null);
        }
//        return RespBean.success(select);
        return new JsonResult<>(OK,"查找数据成功",select);
    }

    @PostMapping("/change_avatar")
    public JsonResult changeAvatar(@RequestParam("file") MultipartFile file,@CaseVip Vip vip, HttpServletRequest request, RedirectAttributes attributes) throws IOException {
        if (vip==null){
            return new JsonResult<>(444,"用户不存在，请重新登录",null);
        }
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            throw new FileEmptyException("上传的头像文件不允许为空");
        }

        // 判断上传的文件大小是否超出限制值
        if (file.getSize() > AVATAR_MAX_SIZE) { // getSize()：返回文件的大小，以字节为单位
            throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
        }

        // 判断上传的文件类型是否超出限制
        String contentType = file.getContentType();
        if (!AVATAR_TYPES.contains(contentType)) {
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：\n" + AVATAR_TYPES);
        }

        //通过servletContext获取服务器中photo目录的路径
//        String parent = session.getServletContext().getRealPath("/classes/static/images/photo/");
//        String parent = request.getServletContext().getRealPath("upload");
        //获取jar包所在目录
//        ApplicationHome h = new ApplicationHome(getClass());
//        File jarF = h.getSource();
//        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
//        String parent = jarF.getParentFile().toString()+"/classes/static/images/book/";
        // 保存头像文件的文件夹
//        File dir = new File("src/main/resources/static/img");
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
//
//        // 保存的头像文件的文件名
//        String originalFilename = file.getOriginalFilename();
//
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String filename = UUID.randomUUID().toString() + suffix;
//
//        // 创建文件对象，表示保存的头像文件
//        File dest = new File(dir, filename);
//
////        System.out.println(parent);
//        // 执行保存头像文件
//        file.transferTo(dest);
//
//        // 头像路径
//        String avatar =  "/img/" + filename;



        // 上传文件/图像到指定文件夹（这里可以改成你想存放地址的相对路径）
        File savePos = new File("hou/src/main/resources/static/imgs");
        if(!savePos.exists()){  // 不存在，则创建该文件夹
            savePos.mkdir();
        }
        // 获取存放位置的规范路径
        String realPath = savePos.getCanonicalPath();
        //获取图片名
        String originalFilename = file.getOriginalFilename();
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
        // 上传该文件/图像至该文件夹下
        file.transferTo(new File(realPath+"/"+originalFilename));
        attributes.addFlashAttribute("message","添加成功！");
//        return "redirect:/admin/pictureWall";
        String avatar =  "/imgs/" + originalFilename;

        System.out.println(realPath);

//        // 返回成功头像路径
//        String avatar = taomiGoodsService.changeAvatar(file, request);
        return new JsonResult<>(OK,"返回头像地址成功",avatar);
    }

//    @RequestMapping("/tupian")

}
